package net.cloudcodex.server.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.cloudcodex.server.Context;
import net.cloudcodex.server.data.Data;
import net.cloudcodex.server.data.Data.Campaign;
import net.cloudcodex.server.data.Data.Scene;
import net.cloudcodex.server.data.Data.User;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Key;

/**
 * Abstract class for services.
 * @author Thomas
 */
public class AbstractCampaignService extends AbstractService {

	/**
	 * @param store Google AppEngine datastore.
	 */
	public AbstractCampaignService(DatastoreService store) {
		super(store);
	}
	
	protected Key createCharacterKey(long campaignId, long characterId) {
		return Data.Character.createKey(Campaign.createKey(campaignId), characterId);
	}

	protected Key createSceneKey(long campaignId, long sceneId) {
		return Scene.createKey(Campaign.createKey(campaignId), sceneId);
	}

	protected boolean isOwner(Context context, Data.Character character) {
		if(character == null || context == null) {
			return false;
		}
		final User user = context.getUser();
		return user == null ? false : user.getKey().equals(character.getOwner());
	}

	/**
	 * @param context execution context, holds the current user.
	 * @param campaign campaign to test.
	 * @return <code>true</code> if the current user is the campaign's GM.
	 */
	public boolean isGameMaster(Context context, Data.Campaign campaign) {
		if(context != null && campaign != null) {
			final Data.User user = context.getUser();
			final Key masterKey = campaign.getMaster();
			if(user != null && masterKey != null) {
				return masterKey.equals(user.getKey());
			}
		}
		return false;
	}

	/**
	 * Utility method, removes NPC from a list of characters.
	 */
	protected List<Data.Character> removeNPCs(List<Data.Character> characters) {
		
		if(characters == null) {
			return null;
		}
		
		final List<Data.Character> pcs = new ArrayList<Data.Character>(characters);
		final Iterator<Data.Character> ipcs = pcs.iterator();
		
		while(ipcs.hasNext()) {
			if(ipcs.next().getOwner() == null) {
				ipcs.remove();
			}
		}
		
		return pcs;
	}
}
